var express = require('express');
var router = express.Router();
const mysql = require('../utils/mysql')
const jiami = require('../utils/jiami');
const jwt = require('jsonwebtoken');
const { expressjwt } = require('express-jwt');

const upload = require('../utils/upload');


const secretKey = 'hello';


// 用户注册
router.post('/userreg', async function (req, res) {
  // 获取从客户端传入的用户名和密码
  let { username, password } = req.body;
  // // 将用户名和密码插入数据库中的users表
  // const result = await mysql(`insert into users (username,password,createTime,updateTime) values (?,?,now(),now())`, [username, password]
  // )
  if (username.lengtn < 2 || password.lengtn < 2) {
    res.json({
      flag: false,
      msg: '用户名无效，请重新输入'
    })
  } else {
    // 判断用户名是否重复
    const [{ count }] = await mysql('select count(*) as count from users where username=?', [username])
    if (count > 0) {
      res.json({
        flag: false,
        msg: '用户名重复，请重新输入'
      })
    } else {
      // 正常注册
      await mysql(`insert into users (username,password,createTime,updateTime) values (?,?,now(),now())`, [username, jiami(password)]
      )
      res.json({
        flag: true,
        msg: '用户注册成功'
      })
    }

  }
}
)

// 用户登录
router.post('/userlogin', async function (req, res) {
  // 获取从客户端传入的用户名和密码
  let { username, password } = req.body;
  if (username.lengtn < 2 || password.lengtn < 2) {
    res.json({
      flag: false,
      msg: '用户名或密码格式不正确'
    })
  } else {
    const result = await mysql('select * from users where username=? and password=?', [username, jiami(password)]);
    if (result.length > 0) {
      res.json({
        flag: true,
        msg: '登录成功',
        data: {
          token: jwt.sign({ username: username, id: result[0].id }, secretKey, { expiresIn: '24h' })
        }
      })
    } else {
      res.json({
        flag: false,
        msg: '用户名或密码不正确',
      })
    }
  }
})
// token验证
router.all('*', expressjwt({
  secret: secretKey,
  algorithms: ['HS256']
}))
router.all('/getdata', async function (req, res) {
  res.json(req.auth)
})
// 上传文件
// router.post('/upload', upload.fields(
//   [
//     { name: 'avatar', maxCount: 2 }, { name: 'img', maxCount: 1 }
//   ]), function (req, res) {
//     res.json({
//       files: req.files,
//       body: req.body,
//     })
//   })


// 获取用户信息
router.get('/getUserInfo', async function (req, res) {
  // 获取当前用户id
  const userid = req.auth.id;
  // 判断userinfo表里有没有对应的记录
  const user = await mysql('select * from userinfo where userid=?', [userid]);
  if (user.length > 0) {
    // 如果找到了
    res.json({
      flag: true,
      data: user[0]
    })
  } else {
    // 如果没找到，数据插入到表里
    await mysql('insert into userinfo (createTime,updateTime,userid) values (now(),now(),?)', [userid])
    res.json({
      flag: true,
      data: {}
    })
  }
}
)

// 更新用户信息
router.post('/updateUserInfo', upload.single('avatar'), async function (req, res) {
  let { nickname, gender, birthday } = req.body;
  let avatar = '';
  if (req.file) {
    avatar = req.file.destination.slice(6) + req.file.filename;
  }
  let userid = req.auth.id;
  // 更新数据库
  const arrField = [];
  const arrValues = [];
  arrField.push('nickname=?');
  arrValues.push(nickname);
  if (gender) {
    arrField.push('gender=?');
    if (gender == 'male') {
      arrValues.push(false);
    } else {
      arrValues.push(true);
    }
  }
  if (birthday) {
    arrField.push('birthday=?');
    arrValues.push(new Date(birthday));
  }
  if (avatar) {
    arrField.push('avatar=?');
    arrValues.push(avatar);
  }
  arrValues.push(userid);

  let sql = 'update userinfo set updateTime=now(),';
  sql += arrField.join(',');
  sql += ' where  userid=?'
  await mysql(sql, arrValues);
  // console.log(result);
  res.json({
    flag: true,
    msg: '更新成功'
  });
})


//新增记事
router.post('/addNote', async function (req, res) {
  //获取当前用户id
  const userid = req.auth.id;
  const { title, content } = req.body;

  //插入数据库
  await mysql('insert into notebook (createTime,updateTime,userid,title,content) values (now(),now(),?,?,?)', [userid, title, content]);
  res.json({
    flag: true,
    msg: '发布成功'
  })

}
)
//获取记录
router.get('/getNote', async function (req, res) {
  const userid = req.auth.id;
  let { search_string, page, per_page } = req.query;
  if (!search_string) {
    search_string = '';
  }

  page = Number(page);
  if (Number.isNaN(page)) {
    page = 1;
  } else {
    if (page < 1) {
      page = 1;
    }
  }

  per_page = Number(per_page);
  if (Number.isNaN(per_page)) {
    per_page = 1;
  } else {
    if (per_page < 5) {
      per_page = 5
    }
  }

  const result = await mysql(
    'select * from notebook where title  like ? or content like ?  and userid = ? ' + 'order by updateTime desc ' + 'limit ?,?',
    [
      '%' + search_string + '%',
      '%' + search_string + '%',
      userid, (page - 1) * per_page,
      per_page
    ]);
  const [{ count: total }] = await mysql('select count(*) as count from notebook where title  like ? or content like ?  and userid = ? ', [
    '%' + search_string + '%',
    '%' + search_string + '%',
    userid])

  res.json
    ({
      flag: true,
      data: {
        list: result,
        total: total,
        pageSize: per_page
      },

    })

})
//删除
router.post('/deleteNote', async function (req, res, next) {
  const { noteid } = req.body;
  await mysql('delete from notebook where id=?', [noteid]);
  res.json({
    flag: true,
    msg: '删除成功'
  })
})
//修改
router.post('/modifyNote', async function (req, res, next) {
  const { title, content, id } = req.body
  await mysql('update notebook set title=?,content=?  where id=?', [title, content, id]);
  res.json({
    flag: true,
    msg: '修改成功'
  })
})
module.exports = router;
